<template>
  <div>

  <el-card>
  <el-row :gutter="30">

    <el-col :span="5">
    <el-input placeholder="读者卡号" v-model="searchForm.readernumber"></el-input>
    </el-col>
    <el-col :span="5">
      <el-input placeholder="账号" v-model="searchForm.username"></el-input>
    </el-col>
    <el-col :span="5">
      <el-input placeholder="电话" v-model="searchForm.tel"></el-input>
    </el-col>
    <el-col :span="2" style="text-align:right">
    <el-button type="success" icon="el-icon-search" @click="handleSearchReader" plain>搜索</el-button>
    </el-col>
    <el-col :span="2" style="text-align:right">
      <el-button type="warning" icon="el-icon-refresh-left" @click="handleResetReader" plain>重置</el-button>
    </el-col>
    <el-col :span="2" style="text-align:right">
      <el-button type="primary" icon="el-icon-plus" @click="addReader" plain>添加</el-button>
    </el-col>
    <el-col :span="2" style="text-align:right">
      <el-button type="danger" icon="el-icon-delete" @click="batchDeleteReader" plain>删除</el-button>
    </el-col>
  </el-row>
  </el-card>

    <el-card>
      <el-row>
      <el-table
          stripe
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="readernumber"
            label="读者卡号"
            width="120">
        </el-table-column>
        <el-table-column
            prop="username"
            label="账号"
            width="100">
        </el-table-column>
        <el-table-column
            prop="realname"
            label="昵称"
            width="100">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="75">
        </el-table-column>
        <el-table-column
            prop="tel"
            label="电话"
            width="120">
        </el-table-column>
        <el-table-column
            prop="registerdate"
            label="办卡时间"
            width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.registerdate) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="160"
            >
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="145"
            header-align="center">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center;">
            <el-button @click="handleClick(scope.row)" type="primary" plain icon="el-icon-edit" circle size="small"></el-button>
            <el-button type="danger" plain icon="el-icon-delete" circle size="small" @click="deleteReader(scope.row)"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
      <el-form :model="readerForm" :rules="rules" ref="readerForm">
        <el-form-item label="读者卡号" :label-width="formLabelWidth" prop="readernumber">
          <el-input v-model="readerForm.readernumber" autocomplete="off" :disabled="isEditing"></el-input>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth" prop="username">
          <el-input v-model="readerForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="realname">
          <el-input v-model="readerForm.realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
          <el-select v-model="readerForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="tel">
          <el-input v-model="readerForm.tel" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="readerForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" plain @click="saveReader">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "ReaderViews",
  data() {
    //自定义校验,验证读者卡号是否重复
    var validateReaderNumber = async (rule, value, callback) => {
      const {data:res} = await this.$axios.get("reader/checkReaderNumber",{params:{readernumber:this.readerForm.readernumber,id:this.readerForm.id}})
      if (res.data==null){
        callback();
      }else if (value===res.data.readernumber && res.data.id !== this.readerForm.id){
        callback(new Error('读者卡号已存在'));
      }else{
        callback();
      }
      };
    //验证账号是否重复
    var validateUsername = async (rule, value, callback) => {
      const {data:res} = await this.$axios.get("reader/checkUsername",{params:{username:this.readerForm.username,id:this.readerForm.id}})
      if (res.data==null){
        callback();
      }else if (value===res.data.username && res.data.id !== this.readerForm.id){
        callback(new Error('账号已存在'));
      }else{
        callback();
      }
    };
    var validateRealname = async (rule, value, callback) => {
      const {data:res} = await this.$axios.get("reader/checkRealname",{params:{realname:this.readerForm.realname,id:this.readerForm.id}})
      if (res.data==null){
        callback();
      }else if (value===res.data.realname && res.data.id !== this.readerForm.id){
        callback(new Error('昵称已存在'));
      }else{
        callback();
      }
    };
    return {
      isEditing: false,
      dialogTitle: '添加读者',
      formLabelWidth: '90px',
      readerForm:{
        readernumber: '',
        username: '',
        realname: '',
        sex: '',
        tel: '',
        registerdate: '',
        email: '',
        birthday:'',
        role:'',
        password:'',
        id:''
      },
      dialogVisible: false,
      tableData: [],
      pageData: {
        currentPage: 1,
        pageSize: 5,
        total:0
      },
      searchForm: {
        readernumber: '',
        username: '',
        tel: ''
      },
      rules: {
        readernumber: [
          { required: true, message: '请输入读者卡号', trigger: 'blur' },
          {validator:validateReaderNumber, trigger: 'change'}
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {validator:validateUsername, trigger: 'change'}
        ],
        realname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
            {validator:validateRealname, trigger: 'change'}
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
    }
  },

  created() {
    this.getReaderList()
  },

  methods: {
    resetForm() {
      this.readerForm = {
        readernumber: '',
        username: '',
        realname: '',
        sex: '',
        tel: '',
        registerdate: '',
        email: '',
        birthday: '',
        role: '',
        password: '',
        icon: '',
        numberborrow:'',
        id: ''
      };
    },
    cancelDialog() {
      this.resetForm(); // 重置表单数据
      this.$refs.readerForm.clearValidate(); // 清除表单验证状态
      this.dialogVisible = false; // 关闭对话框
    },
    saveReader() {
      this.$refs.readerForm.validate(async valid => {
        if (valid) {
          try {
            let res;
            if (this.isEditing) {
              res = await this.$axios.put("reader/updateReader", this.readerForm);
            } else {
              this.readerForm.role = '0';
              this.readerForm.password = '123';
              this.readerForm.icon = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              this.readerForm.registerdate = this.getCurrentDate();
              this.readerForm.numberborrow = '0';
              res = await this.$axios.post("reader/addReader", this.readerForm);
            }
            if (res.data.success) {
              this.$message.success(this.isEditing ? '修改成功' : '添加成功');
              this.dialogVisible = false;
              await this.getReaderList();
            } else {
              this.$message.error(this.isEditing ? '修改失败' : '添加失败');
            }
          } catch (error) {
            this.$message.error(this.isEditing ? '修改失败' : '添加失败');
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    getCurrentDate() {
      const now = new Date();
      return now.toISOString();
    },
    async getReaderList() {
      const params = { ...this.pageData, ...this.searchForm }
      const {data: res} = await this.$axios.get("reader/getReader",{params})
      this.tableData = res.data.records
      this.pageData.total=res.data.total
    },
    handleClose(done) {

      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm(); // 重置表单数据
            this.$nextTick(() => {
              if (this.$refs.readerForm) {
                this.$refs.readerForm.clearValidate(); // 清除表单验证状态
              }
            }); // 清除表单验证状态
            done();
          })
          .catch(_ => {});
    },
    handleSearchReader() {
      this.pageData.currentPage = 1; // 搜索时重置页码
      this.getReaderList();
    },
    handleResetReader() {
      this.searchForm.readernumber = '';
      this.searchForm.username = '';
      this.searchForm.tel = '';
      this.pageData.currentPage = 1; // 重置页码
      this.getReaderList();
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getReaderList()
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getReaderList()
    },
    deleteReader(row){
      this.$confirm('此操作将永久删除该读者, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("reader/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getReaderList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteReader() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的读者');
        return;
      }
      this.$confirm('此操作将永久删除选中的读者, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("reader/batchDeleteReader", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getReaderList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClick(row) {
      this.dialogVisible = true;
      this.isEditing = true;
      this.dialogTitle = '修改读者';
      this.readerForm = { ...row };
    },
    addReader() {
      this.dialogVisible = true;
      this.isEditing = false;
      this.dialogTitle = '添加读者';
      this.resetForm();
      this.$nextTick(() => {
        if (this.$refs.readerForm) {
          this.$refs.readerForm.clearValidate(); // 清除表单验证状态
        }
      });
    }
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
}
.el-card{
  margin-top: 2px;
}
.el-pagination{
  margin-top: 10px;
}
</style>